/*
 * @Author: 凌宇king
 * @Date: 2022-09-18 15:11:13
 * @LastEditTime: 2022-09-25 13:15:56
 */
//加载express
const express = require('express');
//声明路由 
const router = express.Router();
//导入数据模型 
const order = require('../model/order')
//===============API写下面================================================
// 保存订单
router.post('/addOrder', async (req, res) => {
    try {
        await order.create(req.body); res.send('success');
    }
    catch (error) {
        res.send('fail'); console.log(error)
    }
})
//小程序 获取订单数量
router.get('/orderCount', async (req, res) => {
    const { openid, acceptMan, status, completed } = req.query;
    let data = {};//为空，则获取所有订单 
    if (openid) {//获取我的订单 
        data = { openid };
    }
    else if (acceptMan) {//获取我帮助的订单
        data = { acceptMan, completed };
    }
    else if (status) {//获取状态为待帮助的订单 
        data = { status };
    }
    const count = await order.countDocuments(data)
    res.send({ count })
})
//小程序 获取订单 
router.get('/orderList', async (req, res) => {
    const { page, pageSizes, openid, acceptMan, status, completed } = req.query;
    let data = {};//为空，则获取所有订单 
    if (openid) {//获取我的订单 
        data = { openid };
    } else if (acceptMan) {//获取我帮助的订单
        data = { acceptMan, completed };
    } else if (status) {//获取状态为待帮助的订单
        data = { status };
    } try {
        const result = await order.find(data).skip(page).limit(pageSizes).sort({ publicTime: -1 });
        res.send(result)
    }
    catch (err) {
        console.log(err)
        res.send('fail');
    }
})
//获取订单详情
router.get('/orderDetail', async (req, res) => {
    try {
        const mongoose = require('mongoose');
        const result = await order.aggregate([{ $lookup: { from: 'userInfo', localField: 'acceptMan', foreignField: 'openid', as: 'acceptManInfo' } }, { $match: { _id: mongoose.Types.ObjectId(req.query.id) } }])
        res.send({ status: 'success', result });
    }
    catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//接单、确认订单
router.post('/updateOrder', async (req, res) => {
    try {
        const { id, completed, acceptMan, acceptTime, confirmTime, status, isCompleted } = req.body;
        // console.log(completed, status)
        let data = {}
        if (acceptTime) {
            //接单
            data = { acceptMan, acceptTime, status, completed, isCompleted }
        }
        else if (confirmTime) {
            //确认订单 
            data = { confirmTime, status, completed, isCompleted }
        }
        else if (status, completed) {
            data = { status, completed, isCompleted }
        }
        await order.findByIdAndUpdate(id, data)
        res.send('success')
    }
    catch (err) {
        res.send('fail');
        console.log(err);
    }
})
//小程序 删除我的订单 
router.get('/delOrder/:id', async (req, res) => {
    try {
        const id = req.params.id
        await order.deleteOne({
            id
        })
        res.send('success')
    }
    catch (error) {
        console.log(error)
        res.send('fail')
    }
})
//管理后台 数据可视化 统计
router.get('/orderTotal',
    async (req, res) => {
        try {
            const result = await order.aggregate([{
                $group: {
                    _id: '$orderType',
                    orderCounts: { $sum: 1 }
                }
            }])
            res.send({ status: 'success', result })
        } catch (error) {
            console.log(error)
            res.send({ status: 'fail' })
        }
    })
/* 查询当前订单是否完成 */
router.get('/findCompleted', async (req, res) => {
    const Data = await order.find({ _id: req.query.id })
    res.send(Data[0].isCompleted)
})
//统计我完成的订单数量和金额
router.get('/helpedOrders', async (req, res) => {
    try {
        const { acceptMan, completed } = req.query;
        const total = await order.aggregate(
            [{
                $match: {
                    acceptMan, completed
                }
            },
            {
                $group: {
                    _id: '$acceptMan',//按照acceptMan分组 
                    orderCounts: { $sum: 1 }, earnMoney: { $sum: '$payMoney' }
                }
            }]);
        res.send({ status: 'success', total })
    }
    catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
// 结束订单
router.get('/cancleOrder', async (req, res) => {
    const { status, id, completed, isCompleted } = req.query
    await order.updateOne({ _id: id }, {
        $set: {
            status: status,
            completed: completed,
            isCompleted: isCompleted
        }
    })
    res.send('success')
})
//管理后台 获取所有订单 
router.get('/ordGetOrders', async (req, res) => {
    try {
        const { currentPage: page, pagesize } = req.query
        //获取数据库中的记录总数 
        const total = await order.countDocuments()
        //分页获取管理员 
        const result = await order.find().skip((page - 1) * pagesize).limit(pagesize).sort({ time: -1 })
        // console.log(result)
        res.send({ status: 'success', total, result })
    }
    catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//删除订单 
router.get('/delOrder', async (req, res) => {
    const { _id } = req.query
    order.findByIdAndRemove(_id).then(result => {
        res.send('success')
    }).catch(err => { res.send('fail') })
})
//===============API写在上面============================================= 
//导出路由 
module.exports = router